<template>
	<div class="carousel-item-container" ref="container">
		<div class="carousel-item" ref="imgContainer" @mouseenter="handleMouseEnter" @mouseleave="handleMouseLeave">
			<image-loader
				@load="handleImgLoaded"
				:src="carousel.bigImg"
				:placeholder="carousel.midImg"
				:duration="2000"
			></image-loader>
		</div>
		<div class="title animate__fadeInLeft" :class="{ animate__animated: animated_boolean }">
			{{ carousel.title }}
		</div>
		<div class="desc animate__fadeInLeft animate__delay-1s" :class="{ animate__animated: animated_boolean }">
			{{ carousel.description }}
		</div>
	</div>
</template>

<script>
import ImageLoader from '@/components/ImageLoader.vue'
export default {
	name: 'CarouselItem',
	emits: ['load'],
	components: {
		ImageLoader,
	},
	props: {
		carousel: Object,
	},
	methods: {
		handleImgLoaded() {
			this.animated_boolean = true
			// 给父亲组件通知加载完成
			this.$emit('load')
		},
		handleMouseEnter() {
			// 注册事件
			const container = this.$refs.container
			const scaleImg = this.$refs.imgContainer
			container.onmousemove = function (e) {
				// 1.计算中心点到容器边框距离
				const centerX = container.clientWidth / 2
				const centerY = container.clientHeight / 2
				// 2.计算出鼠标偏移容器中心点的百分比
				const percentX = (e.x - container.getBoundingClientRect().left - centerX) / centerX
				const percentY = (e.y - centerY) / centerY
				// 3.获取图片x，y增加的距离为了计算该的距离
				const addDisX = scaleImg.clientWidth - container.clientWidth
				const addDisY = scaleImg.clientHeight - container.clientHeight
				// 4.获取图片元素的一般，用于填充translate(-50%,-50%)的距离
				const imgX = scaleImg.clientWidth / 2
				const imgY = scaleImg.clientHeight / 2
				// 5.最终样式设置，注意百分比要除以2
				scaleImg.style.transform = `translate(-${(addDisX * percentX) / 2 + imgX + 'px'},-${
					(addDisY * percentY) / 2 + imgY + 'px'
				})`
			}
		},
		handleMouseLeave() {
			// 离开时取消mousemove事件
			this.$refs.container.onmousemove = null
		},
	},
	data() {
		return {
			animated_boolean: false,
		}
	},
	destroyed() {
		if (this.$refs.container) {
			this.$refs.container.onmousemove = null
		}
	},
}
</script>

<style lang="less" scoped>
@import '~@/styles/basic/var.less';
.carousel-item-container {
	height: 100%;
	width: 100%;
	position: relative;
	overflow: hidden;
	.carousel-item {
		width: 120%;
		height: 120%;
		position: absolute;
		// 初始值居中
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
	}
	img {
		width: 100%;
		height: 100%;
	}
	.title,
	.desc {
		color: lighten(@gray, 10%);
		position: absolute;
		left: 30px;
		text-shadow: 2px 0 0 1px rgba(0, 0, 0, 0.5), -2px 0 0 1px rgba(0, 0, 0, 0.5), 0 2px 0 1px rgba(0, 0, 0, 0.5),
			0 -2px 0 1px rgba(0, 0, 0, 0.5);
		white-space: nowrap;
		pointer-events: none;
	}
	.title {
		font-size: 2em;
		top: calc(50% - 40px);
	}
	.desc {
		font-size: 1.2em;
		top: calc(50% + 20px);
	}
}
</style>
